﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using dotNET.Repository;
using Microsoft.Extensions.DependencyInjection;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using dotNET.Application.App;
using dotNET.Application.Infrastructure;
using dotNET.Data;
using Microsoft.Extensions.DependencyInjection.Extensions;
using dotNET.Utility.Cache;
using Microsoft.AspNetCore.Mvc;
namespace conan.Saas
{
    public static class AutofacExt
    {
        private static IContainer _container;
        public static IContainer InitAutofac(IServiceCollection services)
        {
            var builder = new ContainerBuilder();
            services.AddTransient(typeof(IRepositoryBase<>), typeof(RepositoryBase<>));
            var IControllerType = typeof(ControllerBase);
            builder.RegisterAssemblyTypes(System.Reflection.Assembly.Load("conan.Saas")).Where(t =>
                            IControllerType.IsAssignableFrom(t) && t != IControllerType).PropertiesAutowired();
            services.AddSingleton(typeof(ICacheService), new RedisCacheService());
            var assemblys = System.Reflection.Assembly.Load("dotNET.Application");
            var baseType = typeof(IDependency);
            builder.RegisterAssemblyTypes(assemblys)
             .Where(m => baseType.IsAssignableFrom(m) && m != baseType).PropertiesAutowired()
             .AsImplementedInterfaces().InstancePerDependency();
            if (services.All(u => u.ServiceType != typeof(IHttpContextAccessor)))
            {
                services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));
            }
            builder.Populate(services);
            _container = builder.Build();
            return _container;
        }
        /// <summary>
        /// 从容器中获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
        }
    }

    ///// <summary>
    ///// 重写依赖注入的业务
    ///// </summary>
    //public class Evolution : Module
    //{
    //    protected override void Load(ContainerBuilder builder)
    //    {
    //        var assemblys = System.Reflection.Assembly.Load("dotNET.Application");//获取ShareYunSourse.Application 程序集，ShareYunSourse.Application 是类库名
    //        var baseType = typeof(IDependency);//IDependency 是一个接口
    //        builder.RegisterAssemblyTypes(assemblys)
    //         .Where(m => baseType.IsAssignableFrom(m) && m != baseType)
    //         .AsImplementedInterfaces().InstancePerDependency();
    //    }
    //}
}
